'use strict';

/**
 * @ngdoc service
 * @name myAppApp.Util
 * @description
 * # Util
 * Service in the myAppApp.
 */
angular.module('jgappApp').service('Util',
    function ($document, $compile, $q, $rootScope, loginService, $timeout, $window, $location, $http, openApi, localStorageService, logList, appVersion, Modulemap) {
        var body = $document.find('body');

        var Util = {
            FK_MODULE: {
                url: openApi.getRelModule_fk,
                name: "FK_MODULE"
            },
            JK_MODULE: {
                url: openApi.getRelModule_jk,
                name: "JK_MODULE"
            },
            CC_MODULE: {
                url: openApi.getRelModule_cc,
                name: "CC_MODULE"
            },
            UC_MODULE: {
                url: openApi.useCarrel,
                name: "UC_MODULE"
            },
            TCSQ_MODULE: {
                url: openApi.commisionApplyrel,
                name: "TCSQ_MODULE"
            },
            OTH_MODULE: {
                url: openApi.getRelModule_oth,
                name: "OTH_MODULE"
            },
            CADUIT_MODULE: {
                url: openApi.getRelModule_caduit,
                name: "CADUIT_MODULE"
            },
            BX_MODULE: {
                url: openApi.getRelModule_bx,
                name: "BX_MODULE"
            },
            READ: "read",
            CHECK: "check",
            AUDIT: "audit",
            SYNCAUDIT: "syncAduit",
            CAUDIT: "caduit",
            UPDATE: "update",
            init: function () {
                document.addEventListener("backbutton", Util.backbuttonHandle, false);
                // 初始化极光推送通知
                Util.initNotification();
                // ios平台下功能
                if (window.device && window.device.platform == "iOS") {
                    // 如果是iOS平台则使用后台运行插件
                    Util.setbackgroundMode();
                    if (cordova.InAppBrowser) {
                        window.open = cordova.InAppBrowser.open;
                    }
                } else if (window.device && window.device.platform == "Android") {
                    // 如果是android平台则使用后台开启服务使应用保持后台运行
                    Util.setbackgroundService();
                }
            },
            setbackgroundService: function () {
                var myService;
                if (cordova.plugins) {
                    myService = cordova.plugins.myService;
                    go();
                }
                function go() {
                    myService.getStatus(function (r) {
                        startService(r)
                    }, function (e) {
                        displayError(e)
                    });
                };
                function startService(data) {
                    if (data.ServiceRunning) {
                        enableTimer(data);
                    } else {
                        myService.startService(function (r) {
                            enableTimer(r)
                        }, function (e) {
                            displayError(e)
                        });
                    }
                }
                function enableTimer(data) {
                    if (data.TimerEnabled) {
                        registerForUpdates(data);
                    } else {
                        myService.enableTimer(8000, function (r) {
                            registerForUpdates(r)
                        }, function (e) {
                            displayError(e)
                        });
                    }
                }
                function registerForUpdates(data) {
                    if (!data.RegisteredForUpdates) {
                        myService.registerForUpdates(function (r) {
                            updateHandler(r)
                        }, function (e) {
                            handleError(e)
                        });
                    }
                }
                function updateHandler(data) {
                    if (data.LatestResult != null) {
                        try {
                            console.log(data.LatestResult.Message)
                        } catch (err) { }
                    }
                }
            },
            setbackgroundMode: function () {
                if (cordova.plugins && cordova.plugins.backgroundMode) {
                    cordova.plugins.backgroundMode.configure({
                        silent: true
                    })
                    cordova.plugins.backgroundMode.enable();
                    cordova.plugins.backgroundMode.ondeactivate = function () {
                        console.log("ondeactivate")
                    };
                    cordova.plugins.backgroundMode.onactivate = function () {
                        console.log("onactivate")
                    };
                }
            },
            initNotification: function () {
                if (window.plugins && window.plugins.jPushPlugin) {
                    window.plugins.jPushPlugin.init();
                    document.addEventListener("jpush.receiveNotification", Util.onReceiveNotification, false);
                    document.addEventListener("jpush.receiveMessage", Util.onReceiveMessage, false);
                    document.addEventListener("jpush.openNotification", Util.onOpenNotification, false);
                }
            },
            onReceiveNotification: function () {
                console.log("onReceiveNotificationonReceiveNotification")
            },
            onReceiveMessage: function () {
                console.log("onReceiveMessageonReceiveMessage")
            },
            onOpenNotification: function (event) {
                console.log("onOpenNotification")
                var content;
                if (window.device.platform == "Android") {
                    var data = window.plugins.jPushPlugin.openNotification;
                    content = data.extras["cn.jpush.android.EXTRA"];
                } else {
                    content = event;
                }
                if (window.plugins.jPushPlugin) {
                    window.plugins.jPushPlugin.getApplicationIconBadgeNumber(function (data) {
                        if (data == 0) {
                            return;
                        }
                        window.plugins.jPushPlugin.setBadge(data - 1)
                        window.plugins.jPushPlugin.setApplicationIconBadgeNumber(data - 1)
                    })
                }
                // 验证是否过期，没有过期则直接进入视图，过期了则重新登录
                loginService.checkExpired().then(function (data) {
                    if (!data) {
                        loginService.login().then(function (data) {
                            if (data == "success") {
                                Util.goView(content);
                            } else {
                                $location.path("login/login");
                            }
                        })
                    } else {
                        Util.goView(content);
                    }
                })
            },
            isFile: function (v) {
                return /(.+)\.(docx|ppt|doc|xls|zip|rar|xlsx|et|pptx|pdf|wps|txt)$/gi.test(v);
            },
            isImg: function (v) {
                return /(.+)\.(jpg|png|gif|jpeg)$/gi.test(v);
            },
            openExpress: function (id) {
                $location.path("/openfile/openfile/express/" + id);
                // window.open(url, '_system', 'location=no');
            },
            goView: function (data) {
                var viewName;
                viewName = Util.getViewNameFromNotice(data);
                if (viewName) {
                    $timeout(function () {

                        // 如果不replace的话连续点击两个消息通知再返回时候会出现问题
                        // 如果replace的话最开始进入的时候不能返回，因为没有历史了
                        if ($location.path() == "/index/index" || $location.path() == "/login/login") {
                            $location.path(viewName + "/" + data.dealId);
                        } else {
                            $location.path(viewName + "/" + data.dealId).replace();
                        }
                    }, 300)
                } else {
                    Util.Toast("移动端暂不支持该流程的审批，请您在电脑上完成该操作");
                }
            },
            getViewNameFromNotice: function (item) {
                var viewName;
                var itemObj;
                // 先清除缓存数据
                Util.clearTVType()
                if (item.businessType == "SYSTEM_NOTICE") {
                    viewName = "/work/systemnotice"
                } else {
                    itemObj = Modulemap.getViewNameAndIcon(item.formKey);
                    switch (item.formType) {
                        case "write": //待审批
                            Util.setTVType(Util.UPDATE)
                            viewName = itemObj.viewName;
                            break;
                        case "read": //待审批
                            Util.setTVType(Util.READ)
                            viewName = itemObj.checkViewName;
                            break;
                        case "aduit": //审批
                            Util.setTVType(Util.AUDIT)
                            viewName = itemObj.checkViewName;
                            break;
                        case "caduit":
                            Util.setTVType(Util.CAUDIT)
                            viewName = itemObj.checkViewName;
                            break;
                        case "syncAduit": //并行审批
                            Util.setTVType(Util.SYNCAUDIT)
                            viewName = itemObj.checkViewName;
                            break;
                        case "view": //自定义流程审批
                            Util.setTVType(Util.CHECK)
                            viewName = itemObj.checkViewName;
                            break;
                        default:
                    }
                    localStorageService.set("iconUrl", item.formKey);
                }
                return viewName;
            },

            logoutUser: function (callback) {
                $http.get(openApi.logout).success(function (data, status, headers, config) {
                    if (data.logout) {
                        $window.localStorage.removeItem("userinfo")
                        $window.localStorage.removeItem("saveuser")
                        localStorageService.clearAll();
                        if (callback) {
                            callback()
                        }
                        return;
                    }
                });
            },
            dateFormat: function (date, fmt) {
                if (!date) {
                    date = new Date();
                } else if (typeof date == "string") {
                    date = new Date(date);
                }
                var o = {
                    "M+": date.getMonth() + 1, //月份 
                    "d+": date.getDate(), //日 
                    "h+": date.getHours(), //小时 
                    "m+": date.getMinutes(), //分 
                    "s+": date.getSeconds(), //秒 
                    "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
                    "S": date.getMilliseconds() //毫秒 
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            },
            checkVersion: function () {
                var remind = true;
                remind = Util.checkUpdateremind();
                if (!remind) {
                    return;
                }
                Util.checkUpate().then(function () {
                    Util.setUpdateremind()
                });

            },
            checkUpate: function () {
                var delay = $q.defer();
                var param = {};
                var platform = Util.getPlatform();
                appVersion.getAppVersion().then(function (data) {
                    param.client = platform;
                    param.versionNo = data;
                    // ios的更新可以通过appstore自动更新
                    // if (platform == "ios") {
                    //     return
                    // }
                    appVersion.checkAppVersion(param).then(function (data) {
                        // 如果有result字段说明需要更新否则就不需要更新
                        if (data.result) {
                            Util.appdownLoad = data.result.value
                            if (navigator.notification) {
                                navigator.notification.confirm(
                                    data.result.text || "新版本更新",
                                    Util.getNewVersion,
                                    '发现新版本', ['更新', '取消']
                                )
                            }
                            delay.resolve(1);
                        } else {
                            delay.resolve(0);
                        }
                    })
                })
                return delay.promise;
            },
            checkUpdateremind: function (value) {
                var needremind = false,
                    curDate, lastDate,
                    appRemindDate;
                appRemindDate = $window.localStorage.getItem("appRemindDate");
                if (!appRemindDate) {
                    needremind = true;
                } else {
                    curDate = Util.dateFormat(new Date(), "yyyy-MM-dd")
                    lastDate = Util.dateFormat(appRemindDate, "yyyy-MM-dd")
                    if (curDate != lastDate) {
                        needremind = true;
                    }
                }
                return needremind;
            },
            // 设置已经提醒了
            setUpdateremind: function () {
                var appRemindDate, appRemindDateStr;
                appRemindDate = new Date();
                appRemindDateStr = Util.dateFormat(appRemindDate, "yyyy-MM-dd")
                $window.localStorage.setItem("appRemindDate", appRemindDateStr);
            },
            getNewVersion: function (value) {
                if (value == 1) {
                    window.open(Util.appdownLoad, '_system', 'location=no');
                }
            },
            getPlatform: function () {
                var platform = "android"
                if (navigator.userAgent.match(/(Android)/)) {
                    platform = "android"; //android
                } else if (navigator.userAgent.match(/(iPad|iPhone)/)) {
                    platform = "ios"; //ios
                }
                return platform
            },
            backbuttonHandle: function (e) {
                Util.goBack();
                e.preventDefault();
            },
            Toast: function (info, option) {
                var time = option && option.time || 2000
                var modalEl = angular.element('<div class="fade toast-wrapper">' + info + '</div>');
                var scope = option && option.scope || $rootScope.$new();
                $compile(modalEl)(scope);
                body.append(modalEl);
                $timeout(function () {
                    modalEl.remove();
                    option && option.callback && option.callback.call(scope);
                }, time);
            },
            showFile: function (scope) {
                var container = angular.element(document.querySelector('div[ng-view]'));
                $rootScope.showMasker = true;
                var template = '<div class="file-wrapper">' +
                    '<div class="img-wrapper">' +
                    '<div class="del-btn icon_del1 lh30" ng-click="closefile()">del</div>' +
                    '<img err-src="images/404.png" ng-src="{{src}}" alt="" width="100%" ng-pinch-zoom max-scale="4">' +
                    '</div>' +
                    '</div>'
                //We don't have the scope we're gonna use yet, so just get a compile function for modal
                $rootScope.fileEl = angular.element(template);
                var newscope = scope || $rootScope.$new();
                $compile($rootScope.fileEl)(newscope);
                container.append($rootScope.fileEl);
            },
            hideFile: function (scope) {
                $rootScope.showMasker = false;
                $rootScope.fileEl.remove();
            },
            showAudit: function (option) {
                var scope = option && option.scope || $rootScope.$new();
                var auditContainer = angular.element(document.querySelector('.container .list'));
                var template = '<div class="audit mt10 task-detail-section">' +
                    '<div class="audit-btn flex tc mt10">' +
                    '<div class="confirm {{item.className}}" ng-click="check(item)" ng-repeat="item in TaskReview.result.operations"><img err-src="images/404.png" ng-src={{item.picScr}} alt="" ng-if="item.picScr"> {{item.name}}</div>' +
                    '</div>' +
                    '</div>'
                //We don't have the scope we're gonna use yet, so just get a compile function for modal
                var modalEl = angular.element(template);
                $compile(modalEl)(scope);
                auditContainer.append(modalEl);
            },
            showAuditDailog: function (option) {
                var title = option.title || "审批意见";
                var container = angular.element(document.querySelector('div[ng-view]'));
                var template = '<div class="audit-dailog task-detail-section" ng-show="showDailog">' +
                    '<div class="audit-title">' + title + '</div>' +
                    '<textarea cols="30" rows="10" ng-model="auditText" placeholder=' + title + '></textarea>' +
                    ' <div class="audit-btn flex tc mt10">' +
                    '<div class="confirm" ng-click="confirm()">确定</div>' +
                    '<div class="cancel" ng-click="cancel()">取消</div>' +
                    '</div>' +
                    '</div>'
                //We don't have the scope we're gonna use yet, so just get a compile function for modal
                var modalEl = angular.element(template);
                var scope = option && option.scope || $rootScope.$new();
                $compile(modalEl)(scope);
                container.append(modalEl);
            },
            chooseFile: function (option) {
                $rootScope.showMasker = true;
                var container = angular.element(document.querySelector('div[ng-view]'));
                var template = '<div class="confirm-dailog tc">' +
                    '<div class="confirm-title lh40 celled">上传附件</div>' +
                    '<div class="icon_del1"  ng-click="cancel()"></div>' +
                    '<div class="dailog-content">请选择上传附件类型</div>' +
                    '<div class="confirm-btn mt10">' +
                    '<div class="confirm btn"  ng-click="choosePic(2)">相册</div>' +
                    '<div class="cancel btn"  ng-click="choosePic(1)">拍照</div>' +
                    '</div>' +
                    '</div>'
                //We don't have the scope we're gonna use yet, so just get a compile function for modal
                $rootScope.fileEl = angular.element(template);
                var scope = option && option.scope || $rootScope.$new();
                $compile($rootScope.fileEl)(scope);
                container.append($rootScope.fileEl);
            },
            showAddFile: function (option) {
                var container = angular.element(document.querySelector('.log-list'));
                var template = '<div class="list-item list-item-textarea" file-upload file-data="attachmentName" maxnum=1></div>'
                //We don't have the scope we're gonna use yet, so just get a compile function for modal
                var modalEl = angular.element(template);
                var scope = option && option.scope || $rootScope.$new();
                $compile(modalEl)(scope);
                container.append(modalEl);
            },
            getTabIndex: function () {
                var index;
                index = localStorageService.get("tabIndex");
                return index;
            },
            setTabIndex: function (index) {
                localStorageService.set("tabIndex", index);
            },
            clearTabIndex: function () {
                localStorageService.remove("tabIndex");
            },
            REGEX: {
                phone: /^1[3,5,8][0-9]{9}$/
            },
            isNullBbj: function (data) {
                var testData = true;
                if (angular.isArray(data)) {
                    testData = !data.length
                }
                if (angular.isObject(data)) {
                    testData = !Object.keys(data).length
                }
                return testData;
            },
            checkDays: function (data) {
                var check = true;
                if (((data * 10) % 5) !== 0) {
                    check = false;
                }
                return check;

            },
            logout: function () {
                Util.Toast("帐号过期，请重新登录", {
                    callback: function () {
                        $location.path("login/login");
                    }
                });
            },
            // 获取各种类别的key,value值
            getKeyValue: function (param, callback) {
                var data = localStorageService.get(JSON.stringify(param));
                if (data && callback) {
                    callback(data);
                    return
                }
                $http({
                    method: 'GET',
                    url: openApi.getKeyType,
                    params: param
                }).then(function (data, status, headers, config) {
                    console.log(data)
                    var data = data.data
                    if (data.logout) {
                        Util.logout();
                        return;
                    }
                    if (data.success) {
                        // 底部关联文件获取
                        localStorageService.set(JSON.stringify(param), data);
                        if (callback) {
                            callback(data);
                        }
                    }
                }, function errorCallback(response) {
                    // called asynchronously if an error occurs
                    // or server returns response with an error status.
                });

            },
            getPerformanceList: function (param, callback) {
                $http.get(param.url + "?id=" + param.params.id).success(function (data, status, headers, config) {
                    console.log(data)
                    if (data.logout) {
                        Util.logout();
                        return;
                    }
                    if (data.success) {
                        if (callback) {
                            callback(data);
                        }
                    }
                }).error(function (data, status, headers, config) {
                    // Util.Toast("no data!");
                });

            },
            getModuleRel: function (relModule, callback) {
                var relModuleData = localStorageService.get("relModuleData" + relModule.name);
                if (relModuleData && relModuleData.success) {
                    if (callback) {
                        callback(relModuleData);
                        return
                    }
                }
                $http.get(relModule.url).success(function (data, status, headers, config) {
                    console.log(data)
                    if (data.logout) {
                        Util.logout();
                        return;
                    }
                    if (data.success) {
                        localStorageService.set("relModuleData" + relModule.name, data);
                        if (callback) {
                            callback(data);
                        }
                        // 底部关联文件获取
                    }
                }).error(function (data, status, headers, config) {
                    // Util.Toast("no data!");
                });

            },
            // 获取证件类别
            getcerTypeList: function (param, callback) {
                var cerkeyTypeList = localStorageService.get("cerkeyTypeList");
                if (cerkeyTypeList && cerkeyTypeList.success) {
                    if (callback) {
                        callback(cerkeyTypeList);
                        return
                    }
                }
                $http.post(openApi.getCerkey, param).success(function (data, status, headers, config) {
                    if (data.logout) {
                        Util.logout();
                        return;
                    }
                    if (data.success) {
                        // 类别列表，用来过滤
                        localStorageService.set("cerkeyTypeList", data);
                        if (callback) {
                            callback(data);
                        }

                    } else {
                        Util.Toast("操作失败，请稍后尝试");
                    }
                }).error(function (data, status, headers, config) {
                    // Util.Toast("no data!");

                });

            },
            /*
             *type='check'(待审批=已通过=审核中用于查看)
             *type='audit'(用于审核)
             *type='update'(用于修改)
             */
            setTVType: function (type) {
                localStorageService.set("TVType", type);
            },
            getTVType: function () {
                var type;
                type = localStorageService.get("TVType");
                return type;
            },
            clearTVType: function () {
                localStorageService.remove("TVType");
            },
            // 设置关联模块层级，有利于返回最后才删除
            setRelMoNum: function (type) {
                var num;
                num = localStorageService.get("RelMoNum") || 0
                if (type) {
                    num++
                } else {
                    num--
                }
                localStorageService.set("RelMoNum", num);
                return num;
            },
            getRelMoNum: function (type) {
                var num;
                num = localStorageService.get("RelMoNum") || 0
                return num;
            },
            // 保存回显数据
            savaParamForReview: function (params, form_id) {
                params.form_id = form_id
                localStorageService.set("paramsforReview", params)
            },
            // 获取回显数据
            getParamForReview: function (form_id) {
                var returnData = {};
                var data = localStorageService.get("paramsforReview");
                // 如果当前id与页面id一致则返回
                if (data && data.form_id == form_id) {
                    returnData = data;
                }
                return returnData

            },
            goBack: function () {
                if ($location.path() == "/index/index" || $location.path() == "/login/login") {
                    if (navigator.Backbutton) {
                        navigator.Backbutton.goHome(function () {
                            console.log('success')
                        }, function () {
                            console.log('fail')
                        });
                    }
                    return;
                    navigator.notification.confirm(
                        '您确定要退出程序吗？',
                        Util.exitApp,
                        '提示', ['确定', '取消']
                    );
                } else {
                    $window.history.back();
                    $rootScope.showMasker = false;
                    $rootScope.showLoading = false;
                    $rootScope.progressBar = false;
                }
            },
            exitApp: function (button) {
                if (button == 1) {
                    document.removeEventListener("backbutton", Util.backbuttonHandle, false); //注销返回键  
                    navigator.app.exitApp(); //退出app程序  
                }
            },
            // 清除回显数据
            clearParamForReview: function (form_id) {
                localStorageService.remove("paramsforReview")
            },
            // 保存查询参数
            savaDataforsearch: function (params) {
                localStorageService.set("selectedObj", params)
            },
            // 获取已经选择好的参数
            getDataforsearch: function () {
                var data = localStorageService.get("selectedObj") || {};
                return data;
            },
            // 获取已经选择好的参数
            clearDataforsearch: function () {
                localStorageService.remove("selectedObj")
            },
            // property给出时候filter中只有一个值
            filterSelectData: function (data, filter, property) {
                var result = {};
                for (var i in filter) {
                    var tempData = data;
                    if (property) {
                        result[property] = data[i]
                    } else {
                        // 当属姓名是包含着对象时候
                        var arr = i.split(".");
                        var temp;
                        while (arr.length > 0) {
                            temp = arr.shift()
                            tempData = tempData && tempData[temp]
                        }
                        result[filter[i]] = tempData
                    }
                }
                return result;
            },
            saveSelectLists: function (data) {
                localStorageService.set("selectLists", data);
            },
            getSelectLists: function () {
                var selectLists;
                selectLists = localStorageService.get("selectLists");
                return selectLists;
            },
            clearSelectListsh: function () {
                localStorageService.remove("selectLists");
            },
            clearFormData: function () {
                Util.clearParamForReview();
                Util.clearDataforsearch();
                // 证件信息
                Util.clearSelectListsh();
                // 审批人员信息
                Util.clearLocalInfo("SPperson");

                // 如果清除掉会导致关联模块调转回来时候获取不到值
                // Util.clearTVType();
            },
            getIconUrl: function () {
                return localStorageService.get("iconUrl")
            },
            saveLocalInfo: function (key, data) {
                localStorageService.set(key, data);
            },
            getLocalInfo: function (key) {
                var data;
                data = localStorageService.get(key) || {};
                return data
            },
            clearLocalInfo: function (key) {
                localStorageService.remove(key);
            },
            mergeArr: function (dist, src, type) {
                var destArr = [];
                if (Array.isArray(src)) {
                    if (src.length < 1) {
                        return dist
                    }
                } else {
                    return dist
                }
                dist.forEach(function (distitem, index) {
                    var check = false;
                    src.forEach(function (srcitem, index) {
                        if (distitem[type] == srcitem[type]) {
                            check = true;
                        }
                    });
                    if (!check) {
                        destArr.push(distitem);
                    };
                });
                dist = src.concat(destArr)
                return dist

            },
            getkeyFromValue: function (obj, value) {
                var key;
                obj.forEach(function (item, index) {
                    if (item.value == value) {
                        key = item.key;
                        return
                    }
                });
                return key;
            },
            getDetailData: function (id, callback) {
                var TVtype;
                TVtype = Util.getTVType(); //根据页面的来源来判断是发起的流程还是修改的流程，如果是发起的则不管，如果是修改的则获取数据用来回显
                var result, selectData;
                result = Util.getParamForReview(id);
                selectData = Util.getDataforsearch();
                // 如果有两个选择项目的话selectTabContent的值不固定
                // 关联模块名称
                // result.relatedModuleName = selectData.selectTabContent || "";
                // 关联模块标识
                // result.relatedModule = selectData.selectTab || "";
                result = angular.extend(result, selectData.filterData);
                // 如果有缓存则用缓存，没有缓存则判断如果要回显则请求数据否则发起流程不管
                if (TVtype == Util.UPDATE && !result.taskId) {
                    var param = {};
                    param.taskId = id
                    $http.get(openApi.getTaskInfo, {
                        params: param
                    }).
                        success(function (data, status, headers, config) {
                            if (data.logout) {
                                Util.logout();
                                return;
                            }
                            if (data.success) {
                                var param = {};
                                param.taskId = data.result.task && data.result.task.id;
                                param.operationId = data.result.operations[0].id
                                var key = data.result.formKey || data.result.currentObjectName;
                                if (!data.result[key]) {
                                    // 提交时候发生了异常key值都在task上面
                                    key = "task";
                                    Util.Toast("该流程在提交的过程中出现异常，请在电脑上删除该条数据并重新发起！", {
                                        callback: Util.goBack
                                    })
                                }
                                var result = angular.extend(data.result[key], param);
                                if (callback) {
                                    callback(result);
                                }
                            }
                        }).
                        error(function (data, status, headers, config) { }.bind(this));
                    // 清掉页面来源数据
                    // Util.clearTVType()
                } else {
                    if (callback) {
                        callback(result);
                    }
                }
            },
            showloglist: function (id, callback) {
                var TVtype;
                TVtype = Util.getTVType();
                if (TVtype == Util.UPDATE) {
                    var param = {}
                    var options = {};
                    options.param = {};
                    options.url = openApi.myProcessLogA;
                    options.param.processId = id;
                    options.param.taskId = id;
                    if (callback) {
                        callback(new logList(options))
                    }
                }

            },
            loadingStatus: function (num) {
                var perent = num + "%"
                if (perent == "100%") {
                    $rootScope.progressBar = false;
                    $rootScope.$apply();
                    return
                }
                $rootScope.progressBar = true;
                $rootScope.pm = perent
                $rootScope.$apply();
            },
            showLoadingStatus: function (num) {
                $rootScope.showLoading = true;
                $rootScope.$apply();
            },
            hideLoadingStatus: function (num) {
                $rootScope.showLoading = false;
                $rootScope.$apply();
            },
            isCurId: function (userId) {
                return userId == $rootScope.curUID;
            },
            addTimesamp: function (str) {
                return str + "?pizza=" + Date.now()
            },
            calcDistance: function (v) {
                var str = '';
                if (v) {
                    str = '距离考勤地点';
                    if (v >= 1000) {
                        str = str + (v / 1000).toFixed(1) + '公里'
                    } else {
                        str = str + v + '米'
                    }
                }
                return str;
            }
        };
        return Util
    }
).factory('focus', function ($timeout, $window) {
    return function (id) {
        // timeout makes sure that it is invoked after any other event has been triggered.
        // e.g. click events that need to run before the focus or
        // inputs elements that are in a disabled state but are enabled when those events
        // are triggered.
        $timeout(function () {
            var element = $window.document.getElementById(id);
            if (element)
                element.focus();
        });
    };
});